import React, { useEffect, useState } from "react";

import {
  Button,
  Form,
  Input,
  Card,
  Table,
  Select,
  Row,
  Col,
  message,
} from "antd";
import { SearchOutlined } from "@ant-design/icons";
import {
  getCityDistrictListRequest,
  getHospitalListRequest,
  getProvinceListRequest,
  changeStatusRequest,
} from "@/api/hospital/hospitalList";
import {
  getProvinceListReturnType,
  hospitalListContentType,
  hospitalListItemType,
  searchHospitalParamsType,
} from "@/api/hospital/model/hospitalListTypes";
import { useNavigate } from "react-router-dom";
import { getHosSetListItemType } from "@/api/hospital/model/hospitalSetTypes";
import HospitalSchedule from "./hospitalSchedule";

export default function HospitalList() {
  const navigate = useNavigate();
  const { Option } = Select;
  const [form] = Form.useForm();

  const [hospitalList, setHospitalList] = useState<hospitalListContentType>();
  const [isLoading, setIsLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(3);
  const [total, setTotal] = useState(0);
  const [province, setProvince] = useState<getProvinceListReturnType>([]);
  const [city, setCity] = useState<getProvinceListReturnType>([]);
  const [district, setDistrict] = useState<getProvinceListReturnType>([]);
  const [hosType, setHosType] = useState<getProvinceListReturnType>([]);
  const [search, setSearch] = useState<searchHospitalParamsType>({});
  const [reRender, setReRender] = useState(true);
  useEffect(() => {
    setIsLoading(true);
    const getHosList = async () => {
      const re = await getHospitalListRequest(page, limit, search);
      setHospitalList(re.content);
      setTotal(re.totalElements);
      setIsLoading(false);
      // console.log(re);
    };
    getHosList();
  }, [page, limit, search, reRender]);

  useEffect(() => {
    const getProvince = async () => {
      const re = await getProvinceListRequest();
      setProvince(re);
    };
    getProvince();
  }, []);

  useEffect(() => {
    const getHosType = async () => {
      const re = await getCityDistrictListRequest("10000");
      setHosType(re);
    };
    getHosType();
  }, []);

  const provinceChangeHandle = async (id: string) => {
    const re = await getCityDistrictListRequest(id);
    setCity(re);
    form.setFieldsValue({ cityCode: "", districtCode: "" });
    setDistrict([]);
  };
  const cityChangeHandle = async (id: string) => {
    const re = await getCityDistrictListRequest(id);
    form.setFieldsValue({ districtCode: "" });
    setDistrict(re);
  };

  const formSubmitHandle = (fieldsValue: searchHospitalParamsType) => {
    setSearch(fieldsValue);
  };
  const clearSearchHandle = () => {
    setSearch({});
  };

  const hospitalDetailShowHandle = (id: string) => {
    return () => {
      navigate(`/syt/hospital/hospitalShow/${id}`);
    };
  };

  const hospitalStatusChangeHandle = (id: string, status: 0 | 1) => {
    return async () => {
      await changeStatusRequest(id, status);
      message.success(status ? "上线成功" : "下线成功");
      setReRender(!reRender);
    };
  };

  const HospitalSchedule = (hoscode: string) => {
    return async () => {
      navigate(`/syt/hospital/hospital/hospitalschedule`, {
        state: {
          hoscode,
        },
      });
    };
  };

  const columns = [
    {
      title: "#",
      dataIndex: "index",
      width: 50,
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院Logo",
      dataIndex: "logoData",
      render(logoData: string) {
        return (
          <img
            style={{ width: 100 }}
            src={`data:image/jpeg;base64,${logoData}`}
          />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "等级",
      dataIndex: "param",
      render(param: any) {
        return param.hostypeString;
      },
    },
    {
      title: "详细地址",
      dataIndex: "param",
      render(param: any) {
        return param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render(status: 0 | 1) {
        return status ? "上线" : "下线";
      },
    },
    {
      title: "创建事件",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      dataIdex: "handle",
      fixed: "right" as "right",
      width: 120,
      render(_: any, data: hospitalListItemType) {
        const { id, hoscode } = data;
        return (
          <div>
            <Button type="primary" onClick={hospitalDetailShowHandle(id)}>
              查看
            </Button>
            <Button type="primary" onClick={HospitalSchedule(hoscode)}>
              排班
            </Button>
            <Button
              type="primary"
              onClick={hospitalStatusChangeHandle(
                id,
                data.status === 1 ? 0 : 1
              )}
            >
              {data.status === 0 ? "上线" : "下线"}
            </Button>
          </div>
        );
      },
    },
  ];

  return (
    <div>
      <Card>
        <Form name="basic" form={form} onFinish={formSubmitHandle}>
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item name="provinceCode">
                <Select
                  placeholder="请选择省"
                  allowClear
                  onChange={provinceChangeHandle}
                >
                  {province.map((item) => {
                    return (
                      <Option value={item.value} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="cityCode">
                <Select
                  placeholder="请选择市"
                  allowClear
                  onChange={cityChangeHandle}
                >
                  {city.map((item) => {
                    return (
                      <Option value={item.value} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="districtCode">
                <Select placeholder="请选择区" allowClear>
                  {district.map((item) => {
                    return (
                      <Option value={item.value} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hostype">
                <Select placeholder="医院类型" allowClear>
                  {hosType.map((item) => {
                    return (
                      <Option value={item.value} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="status">
                <Select placeholder="医院状态" allowClear>
                  <Option value={1}>上线</Option>
                  <Option value={0}>下线</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  <SearchOutlined />
                  搜索
                </Button>
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item>
                <Button
                  type="default"
                  htmlType="reset"
                  onClick={clearSearchHandle}
                >
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Table
          columns={columns}
          dataSource={hospitalList}
          rowKey="id"
          scroll={{ x: 1500 }}
          bordered
          loading={isLoading}
          //给表格的配置页码，通过对象配置
          pagination={{
            //当前页码
            current: page,
            //数据的数量
            total,
            //每页多少条
            pageSize: limit,
            //展示更改每页条数的选项（默认total大于50条的时候开启）
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal() {
              return `共${total}条数据`;
            },
            onChange(page: number, limit: number) {
              setPage(page);
              setLimit(limit);
            },
          }}
        />
      </Card>
    </div>
  );
}
